package com.aw.baselib.util

import android.app.Activity
import android.app.ActivityManager
import android.app.Application
import android.content.Context
import com.aw.baselib.base.AwBaseApplication
import java.util.Stack

/**
 * @author : hzw
 * @date : 2020/6/19 10:45
 */
class AwActivityUtil {
    /**
     * 添加Activity
     */
    @Synchronized
    fun addActivity(activity: Activity) {
        stack!!.add(activity)
    }

    /**
     * 移除Activity
     */
    @Synchronized
    fun removeActivity(activity: Activity) {
        stack!!.remove(activity)
    }

    /**
     * 结束指定类名的Activity
     */
    fun finishActivity(cls: Class<*>) {
        for (activity in stack!!) {
            if (activity.javaClass == cls) {
                finishActivity(activity)
                return
            }
        }
    }

    /**
     * 结束指定的Activity
     */
    fun finishActivity(activity: Activity?) {
        if (activity != null) {
            activity.finish()
            stack!!.remove(activity)
        }
    }

    /**
     * 是否存在Activity
     */
    fun containsActivity(cls: Class<*>): Boolean {
        for (activity in stack!!) {
            if (activity.javaClass == cls) {
                return true
            }
        }
        return false
    }

    /**
     * 结束所有Activity
     */
    fun finishAllActivity() {
        for (activity in stack!!) {
            activity?.finish()
        }
        stack!!.clear()
    }

    companion object {
        @JvmStatic
        fun isTopActivity(activity: Activity): Boolean {
            val am = activity.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
            val cn = am.getRunningTasks(1)[0].topActivity
            return cn!!.className.contains(activity.javaClass.name)
        }

        fun isTopActivity(className: String): Boolean {
            val am = AwBaseApplication.instance?.getSystemService(Application.ACTIVITY_SERVICE) as ActivityManager
            val cn = am.getRunningTasks(1)[0].topActivity
            return cn!!.className == className
        }

        private var stack: Stack<Activity>? = null
        private var manager: AwActivityUtil? = null

        @JvmStatic
        @get:Synchronized
        val instance: AwActivityUtil?
            /**
             * 获取实例
             */
            get() {
                if (manager == null) {
                    manager = AwActivityUtil()
                    stack = Stack()
                }
                return manager
            }
    }
}